package cn.xiuxius.embedded.runtime.rtx51;

import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.ui.Gray;
import org.jetbrains.annotations.NotNull;

import java.awt.Color;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TaskHighlightAnnotator implements Annotator {

    // 分组捕获数字部分
    private static final Pattern TASK_PATTERN = Pattern.compile("/\\*\\*\\s*_task_ (\\w+)\\s*\\*\\*/");
    private static final Pattern MALFORMED_TASK_PATTERN = Pattern.compile("/\\*\\*\\s*_task_\\w+\\s*\\*\\*/");


    private static final TextAttributesKey HIDDEN_KEY =
            TextAttributesKey.createTextAttributesKey("TASK_COMMENT_HIDDEN");

    @Override
    public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
        if (!(element instanceof PsiComment)) return;

        String text = element.getText();
        Matcher malformedMatcher = MALFORMED_TASK_PATTERN.matcher(text);
        if (malformedMatcher.find()) {
            int startOffset = element.getTextRange().getStartOffset() + malformedMatcher.start();
            int endOffset = element.getTextRange().getStartOffset() + malformedMatcher.end();
            holder.newAnnotation(HighlightSeverity.ERROR, "_task_ format error")
                    .range(new TextRange(startOffset, endOffset))
                    .create();
            return;
        }

        EditorColorsScheme colorsScheme = EditorColorsManager.getInstance().getGlobalScheme();
        Color lightGray = Gray._160;  // 浅灰色
        TextAttributes grayAttributes = new TextAttributes(lightGray, null, null, null, 0);
        colorsScheme.setAttributes(HIDDEN_KEY, grayAttributes);
        Matcher matcher = TASK_PATTERN.matcher(text);
        while (matcher.find()) {
            int elementStart = element.getTextRange().getStartOffset();

            int matchStart = matcher.start();
            int matchEnd = matcher.end();

            TextRange fullRange = new TextRange(elementStart + matchStart, elementStart + matchEnd);

            int numberGroupEndInMatch = matcher.end(1);

            int keywordStart = elementStart + matchStart + text.substring(matchStart, matchEnd).indexOf("_task_");
            int keywordEnd = elementStart + matchStart + numberGroupEndInMatch - matchStart;

            // 两边注释符号及空白用浅灰色
            if (keywordStart > fullRange.getStartOffset()) {
                holder.newSilentAnnotation(HighlightSeverity.INFORMATION)
                        .range(new TextRange(fullRange.getStartOffset(), keywordStart))
                        .textAttributes(HIDDEN_KEY)
                        .create();
            }

            String taskId = matcher.group(1);
            String matchedText = text.substring(matchStart, matchEnd);
            int taskPrefixOffset = matchedText.indexOf("_task_");
            int valueStartOffset = taskPrefixOffset + "_task_".length() + 1; // 加空格

            int startOffset = element.getTextRange().getStartOffset() + matchStart;

            // 1. 灰色高亮：注释起始 `/** `
            if (taskPrefixOffset > 0) {
                holder.newSilentAnnotation(HighlightSeverity.INFORMATION)
                        .range(new TextRange(startOffset, startOffset + taskPrefixOffset))
                        .textAttributes(HIDDEN_KEY)
                        .create();
            }

            // 2. `_task_` 高亮
            holder.newAnnotation(HighlightSeverity.INFORMATION, "Task")
                    .range(new TextRange(startOffset + taskPrefixOffset, startOffset + taskPrefixOffset + 6))
                    .textAttributes(DefaultLanguageHighlighterColors.KEYWORD)
                    .create();

            // 3. `123` or `ABC_DEF` 高亮
            int valueEndOffset = startOffset + matcher.end(1) - matchStart;
            TextAttributesKey valueKey = taskId.matches("\\d+")
                    ? DefaultLanguageHighlighterColors.NUMBER
                    : DefaultLanguageHighlighterColors.CONSTANT;

            holder.newAnnotation(HighlightSeverity.INFORMATION, "Task ID: " + taskId)
                    .range(new TextRange(startOffset + valueStartOffset, valueEndOffset))
                    .textAttributes(valueKey)
                    .create();

            // 4. 灰色高亮：注释结尾 ` **/`
            if (valueEndOffset < startOffset + matchedText.length()) {
                holder.newSilentAnnotation(HighlightSeverity.INFORMATION)
                        .range(new TextRange(valueEndOffset, startOffset + matchedText.length()))
                        .textAttributes(HIDDEN_KEY)
                        .create();
            }
        }
    }

}
